<?php

namespace app\common\entity;

use think\Db;
use think\Model;

class Team extends Model {

    protected $createTime = 'create_time';

    /**
     * @var string 对应的数据表名
     */
    protected $table = 'team';
    protected $auto = ['create_time'];

    //返回原有数据  不自动进行时间转换
    public function getCreateTimeAttr($time) {
        return $time;
    }

    /**
     * 获取列表
     * @param type $page    页数
     * @param type $limit   每页条数
     */
    public function getList($page, $limit) {
        $page = max($page, 1);
        $startLimit = ($page - 1) * $limit;

        $list = $this->field('id,uid,name,declaration')->limit($startLimit, $limit)->order('count DESC,id DESC')->select();
        if (count($list)) {
            $list = $list->toArray();
            $uids = array_column($list, 'uid');
            $userModel = new User();
            $userInfo = $userModel->getUsernameByUids($uids);
            foreach ($list as $k => $v) {
                $list[$k]['username'] = isset($userInfo[$k['uid']]) ? $userInfo[$k['uid']] : '';
            }
        }
        $nextPage = ++$page;
        if (count($list) < $limit) {
            $nextPage = 0;
        }
        $data['list'] = $list;
        $data['nextPage'] = $nextPage;
        return $data;
    }

    public function addTeam($data, User $userInfo) {
        $insertdata = [
            'name' => $data['name'],
            'leader_qq' => $data['qq'],
            'leader_wx' => $data['wx'],
            'leader_mobile' => $data['mobile'],
            'qq_groupid' => $data['groupid'],
            'declaration' => $data['declaration'],
            'uid' => $userInfo->id,
            'team_calculation' => $userInfo->product_rate,
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $model = new Team();
        return $model->insertGetId($insertdata);
    }

}
